<template>
  <div class="st">
    <h4 class="fb">发表评论</h4>
    <hr />
    <!-- 输入框 -->
    <van-cell-group>
      <van-field v-model="value" placeholder="请输入留言" maxlength="50" show-word-limit/>
    </van-cell-group>
    <!-- 发表评论按钮 -->
    <van-button class="fb" type="primary" @click="comment">发表评论</van-button>
    <!-- 评论列表 -->
    <div v-for="(item,index) in commentList" :key="index">
      <div class="title">
        <span>第{{index+1}}楼</span>
        <span>用户：{{item.user_name}}</span>
        <span>发表时间：{{item.add_time.substring(0,10)}}</span>
      </div>
      <div class="body">{{item.content}}</div>
    </div>
    <!-- 加载更多按钮 -->
    <van-button class="fb" plain color="#7232dd" @click="load">加载更多</van-button>
  </div>
</template>
<script>
export default {
  created () {
    this.id = this.$route.params.id
    this.getCommentList()
  },
  data () {
    return {
      // 商品id
      id: '',
      // 输入框输入的值
      value: '',
      // 评论列表
      commentList: [],
      // 获取商品列表
      page: 1
    }
  },
  methods: {
    // 获取评论列表
    async getCommentList () {
      const { data: res } = await this.$axios.get(`/api/getcomments/${this.id}?pageindex=${this.page}`)
      // console.log(res.message)

      // 判断是第一次请求 还是点击了加载更多
      if (this.page === 1) {
        this.commentList = res.message
      }
      this.commentList = this.commentList.concat(res.message)
      console.log(this.commentList)
    },
    // 点击加载更多
    load () {
      this.page++
      this.getCommentList()
    },
    // 发表评论
    async comment () {
      const { data: res } = await this.$axios.post(`/api/postcomment/${this.id}`,
        {
          content: this.value
        })
      if (res.message !== '评论提交成功') return this.$toast.fail('发表评论失败！')
      // console.log(res.message)
      this.value = ''
      this.getCommentList()
      this.$toast.success('评论提交成功')
    }

  }
}
</script>
<style scoped lang="less">
.st{
    padding: 0 5px;
    padding-bottom: 80px;
}
.van-field{
    padding: 10px 16px !important;
}
.fb{
    width: 100%;
    margin: 5px 0;
}
.title{
    height: 30px;
    background-color: #ccc;
    font-size: 12px;
    line-height: 30px;
    span{
        margin-right: 6px;
    }
}
.body{
    line-height: 35px;
    text-indent: 2em;
    font-size: 12px;
}
</style>
